import React from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  TextField,
  Button,
  Divider,
  FormControlLabel,
  Switch,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Alert,
  useTheme,
  SelectChangeEvent
} from '@mui/material';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '../../store';
import { setTheme, setLanguage } from '../../store/slices/appSlice';
import Loading from '../../components/common/Loading';

interface PasswordForm {
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}

const Settings: React.FC = () => {
  const { t, i18n } = useTranslation();
  const dispatch = useDispatch();
  const theme = useTheme();
  const { theme: themeMode, language } = useSelector((state: RootState) => state.app);
  // 暂时注释掉密码修改功能，等待API实现
  // const [changePassword, { isLoading, error, isSuccess }] = useChangePasswordMutation();

  const {
    register,
    handleSubmit,
    watch,
    reset,
    formState: { errors }
  } = useForm<PasswordForm>({
    defaultValues: {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  });

  const newPassword = watch('newPassword');

  const handleThemeChange = () => {
    dispatch(setTheme(themeMode === 'light' ? 'dark' : 'light'));
  };

  const handleLanguageChange = (event: SelectChangeEvent) => {
    const newLanguage = event.target.value as 'zh' | 'en';
    dispatch(setLanguage(newLanguage));
    i18n.changeLanguage(newLanguage);
  };

  const onSubmit = async (data: PasswordForm) => {
    try {
      // 等待API实现
      // await changePassword({
      //   oldPassword: data.oldPassword,
      //   newPassword: data.newPassword
      // }).unwrap();
      reset();
      console.log('Password change submitted:', data);
    } catch (err) {
      console.error('Change password failed:', err);
    }
  };

  return (
    <Container maxWidth="md">
      <Typography variant="h4" component="h1" gutterBottom>
        {t('user.settings.title')}
      </Typography>

      <Box sx={{ mt: 4 }}>
        {/* 主题和语言设置 */}
        <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
          <Typography variant="h6" gutterBottom>
            {t('user.settings.preferences')}
          </Typography>

          <Box sx={{ mb: 3 }}>
            <FormControlLabel
              control={
                <Switch
                  checked={themeMode === 'dark'}
                  onChange={handleThemeChange}
                  color="primary"
                />
              }
              label={t('user.settings.darkMode')}
            />
          </Box>

          <FormControl fullWidth>
            <InputLabel id="language-select-label">
              {t('user.settings.language')}
            </InputLabel>
            <Select
              labelId="language-select-label"
              value={language}
              label={t('user.settings.language')}
              onChange={handleLanguageChange}
            >
              <MenuItem value="zh">中文</MenuItem>
              <MenuItem value="en">English</MenuItem>
            </Select>
          </FormControl>
        </Paper>

        {/* 密码修改 */}
        <Paper elevation={3} sx={{ p: 3 }}>
          <Typography variant="h6" gutterBottom>
            {t('user.settings.password')}
          </Typography>

          {/* 暂时注释掉错误和成功提示，等待API实现 */}
          {/* {error && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {t('user.settings.error')}
            </Alert>
          )}

          {isSuccess && (
            <Alert severity="success" sx={{ mb: 2 }}>
              {t('user.settings.success')}
            </Alert>
          )} */}

          <Box component="form" onSubmit={handleSubmit(onSubmit)}>
            <TextField
              margin="normal"
              required
              fullWidth
              type="password"
              label={t('user.settings.oldPassword')}
              error={!!errors.oldPassword}
              helperText={errors.oldPassword?.message}
              {...register('oldPassword', {
                required: t('user.settings.oldPasswordRequired')
              })}
            />

            <TextField
              margin="normal"
              required
              fullWidth
              type="password"
              label={t('user.settings.newPassword')}
              error={!!errors.newPassword}
              helperText={errors.newPassword?.message}
              {...register('newPassword', {
                required: t('user.settings.newPasswordRequired'),
                minLength: {
                  value: 6,
                  message: t('user.settings.passwordMinLength')
                }
              })}
            />

            <TextField
              margin="normal"
              required
              fullWidth
              type="password"
              label={t('user.settings.confirmPassword')}
              error={!!errors.confirmPassword}
              helperText={errors.confirmPassword?.message}
              {...register('confirmPassword', {
                required: t('user.settings.confirmPasswordRequired'),
                validate: value =>
                  value === newPassword || t('user.settings.passwordMismatch')
              })}
            />

            <Button
              type="submit"
              variant="contained"
              color="primary"
              sx={{ mt: 3 }}
              // disabled={isLoading}
            >
              {t('user.settings.save')}
            </Button>
          </Box>
        </Paper>
      </Box>
    </Container>
  );
};

export default Settings; 